package com.bkgy.modular.httppost;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;

@Slf4j
@Service("httpClientService")
@Transactional
public class HttpClientServiceImpl implements HttpClientService {

    @Override
    public String postJsonRequest(String url, String json, Boolean isLog, String businessType) {

        String responseString = null;
        try {
            final SSLConnectionSocketFactory sslsf;
            try {
                sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                        NoopHostnameVerifier.INSTANCE);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslsf)
                    .build();
            final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(100);
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .setConnectionManager(cm)
                    .build();
            StringBuilder theUrl = new StringBuilder(url);
            HttpPost httpPost = new HttpPost(theUrl.toString());
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(60 * 1000)
                    .setConnectTimeout(60 * 1000)
                    .build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json;charset=UTF-8");

            if (!isLog) {
                httpPost.addHeader("msa-api-access-key", "cfev6xmrxawif1zb");
            } else {
                httpPost.addHeader("msa-api-access-key", "web-common-backend");
            }

            long startTime = System.currentTimeMillis();
            CloseableHttpResponse response = httpClient.execute(httpPost);
            long endTime = System.currentTimeMillis();
            log.debug("请求的时间 ： =========================" + (endTime - startTime) + "ms ============================");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseString = EntityUtils.toString(entity, "UTF-8").replaceAll("\r", "");
                log.debug("URL:" + url + "返回的报文 ：{}", responseString);
            }
            response.close();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
        log.debug("返回参数:" + responseString);

        return responseString;
    }
}
